package com.study.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.study.constant.RedisConstant;
import com.study.dao.SetMealDao;
import com.study.entity.PageResult;
import com.study.entity.QueryPageBean;
import com.study.pojo.Setmeal;
import com.study.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    @Resource(name = "setMealDao")
    private SetMealDao setMealDao;
    @Resource(name = "freemarkerConfig")
    private FreeMarkerConfigurer freemarkerConfig;
    @Value(value = "${out_put_path}")
    private String outPutPath;
    @Resource(name = "jedisPool")
    private JedisPool jedisPool;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.add(setmeal);
        setSetMealAndCheckGroup(setmeal.getId(),checkgroupIds);
        //完成数据库操作后需要将图片名称保存到redis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        generateMobileStaticHtml();
    }

    public void generateMobileStaticHtml(){
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal",setMealDao.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList",setmealList);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    public void generateHtml(String templateName,String htmlName,Map map){
        Configuration configuration = freemarkerConfig.getConfiguration();
        Writer writer = null;
        try {
            Template template = configuration.getTemplate(templateName);
            writer = new FileWriter(new File(outPutPath + File.separator + htmlName));
            template.process(map,writer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }finally {
            try {
                if(writer == null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setMealDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setMealDao.findById(id);
    }

    @Override
    public Map<String, Object> getSetmealReport() {
        Map<String, Object> map = new HashMap<>();
        List<String> nameList = new ArrayList<>();
        List<Map<String, Object>> countList = setMealDao.findSetMealCount();
        for (Map<String, Object> mapList : countList) {
            nameList.add(mapList.get("name").toString());
        }
        map.put("setmealNames",nameList);
        map.put("setmealCounts",countList);
        return map;
    }

    private void setSetMealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("setMealId",id);
            map.put("checkGroupId",checkgroupId);
            setMealDao.setSetMealAndCheckGroup(map);
        }
    }
}
